
import http, { baseParams } from "@/utils/request";
import { UrlLogin } from "@/utils/apiUrl";
import { setUserInfo } from "@/utils/storage";
import { Toast } from "antd-mobile";
import { isEmptyString } from "@/utils/utils";
import AppParams from "@/utils/appParams";
import ZjcUtil from "@/utils/zjcUtil";


//类型：请求成功
export const LOGIN_REQ_SUCCESS = "LOGIN_REQ_SUCCESS"

//类型：请求失败
export const LOGIN_REQ_FAIL = "LOGIN_REQ_FAIL"

//类型：清空请求
export const LOGIN_REQ_CLEAR = "LOGIN_REQ_CLEAR"


/**
 * 登录
 * @param {string} mobile 邮箱
 * @param {string} password 密码
 * @returns thunk
 */
export const doLogin = (mobile, password, reqCallback) => {
    return async dispatch => {
        console.log("doLogin: " + UrlLogin);

        //来源
        const dreferrer = document.referrer || ""

        //组装参数
        const params = baseParams()
        params.mobile = mobile + ""
        params.name = mobile + ""
        params.password = password + ""
        params.chatName = AppParams.chatName + ""
        params.docReferrer = dreferrer + ""

        console.log("=======docReferrer: " + dreferrer)

        //发起请求
        const res = await http.post(UrlLogin, params)
        console.log(res);
        const resCode = parseInt(res.code)
        const resObj = res.data
        const resMsg = res.msg
        console.log("登录回调-结束：=======")

        //保存
        const success = (resCode === 0)
        // dispatch(saveLoginState(resObj, success))

        //如果有错误，提示
        if (!success) {
            if (!isEmptyString(resMsg)) {
                Toast.show(resMsg, 1)
            }
        }

        //保存本地
        if (success) {
            //保存号码
            resObj.mobile = mobile + "";
            resObj.token = res.userId || "";
            setUserInfo(resObj);
        }

        //回调
        reqCallback && reqCallback(success, resObj)
    }
}

/**
 * 将 登录 信息保存到 Redux 中
 * @param {*} data 登录信息 
 * @returns 
 */
export const saveLoginState = (data, success) => {
    return {
        type: success ? LOGIN_REQ_SUCCESS : LOGIN_REQ_FAIL,
        payload: data
    }
}

/**
 * 将 登录 信息保存到 Redux 中
 * @param {*} data 登录信息 
 * @returns 
 */
export const cleanLoginState = () => {
    return {
        type: LOGIN_REQ_CLEAR,
        payload: {}
    }
}